package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.services.IMessageService;
import com.example.forum.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: liuli
 * Date: 2024-08-15
 * Time: 19:51
 */

@Slf4j
@Api(tags = "私信接⼝")
@RestController
@RequestMapping("/message")
public class MessageController {
    // 注⼊业务层
    @Resource
    private IMessageService messageService;
    @Resource
    private IUserService userService;


    /**
     * 发送私信
     *
     * @param receiveUserId 接收用户d
     * @param content 内容
     * @return AppResult
     */
    @ApiOperation("发送私信")
    @PostMapping("/send")
    public AppResult send (HttpServletRequest request,
                           @ApiParam(value = "接收用户Id") @RequestParam(value = "receiveUserId") @NonNull Long receiveUserId,
                           @ApiParam(value = "私信内容") @RequestParam(value = "content") @NonNull String content) {
        // 获取发送用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断是否被禁⾔
        if (user.getState() != 0) {
            // 日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + ", userId = " + user.getId());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 不能给自己发送
        if (user.getId() == receiveUserId) {
            // 日志
            log.warn("不能给⾃⼰发送私信嗷. postUserId = " + user.getId() + ", receiveUserId = " + receiveUserId);
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        // 查询接收用户
        User receiveUser = userService.selectById(receiveUserId);
        // ⽬标用户不存在
        if (receiveUser == null || receiveUser.getDeleteState() != 0) {
            // 日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", receiveUserId = " + receiveUserId);
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        // 调⽤业务层
        messageService.create(message);
        // 返回结果
        return AppResult.success();
    }


    /**
     * 获取未读消息个数
     * @return AppResult<Integer>
     */
    @ApiOperation("获取未读消息个数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount (HttpServletRequest request) {
        // 获取发送用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 查询未读消息个数
        Integer result = messageService.selectUnreadCount(user.getId());
        // 返回结果
        return AppResult.success(result);
    }

    /**
     * 查询用户的所有私信
     * @param request 用户
     * @return 私信集合
     */
    @ApiOperation("查询⽤户的所有私信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        // 获取当前登录用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 获取⽤户私信
        List<Message> result = messageService.selectByReceiveUserId(user.getId());
        // 返回结果
        return AppResult.success(result);
    }


    /**
     * 更新私信状态为已读
     * @param id 私信Id
     * @return AppResult<Message>
     */
    @ApiOperation("更新状态为已读")
    @PostMapping("/markRead")
    public AppResult markRead (HttpServletRequest request,
                               @ApiParam(value = "私信Id") @RequestParam(value = "id") @NonNull Long id) {
        // 根据Id查询私信
        Message message = messageService.selectById(id);

        if(message == null || message.getDeleteState() == 1){
            return  AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }

        // 获取⽤⼾信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 接收⽅不是⾃⼰
        if (user.getId() != message.getReceiveUserId()) {
            // 返回错误结果
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 更新为已读状态:1
        messageService.updateStateById(id, (byte) 1);
        // 返回结果
        return AppResult.success();
    }

    /**
     * 回复私信
     * @param repliedId 要回复的私信Id
     * @param content 私信的内容
     * @return AppResult
     */
    @ApiOperation("回复私信")
    @PostMapping("/reply")
    public AppResult reply (HttpServletRequest request,
                            @ApiParam("要回复的私信Id") @RequestParam("repliedId") @NonNull Long repliedId,
                            @ApiParam("私信的内容") @RequestParam("content") @NonNull String content) {
        // 校验当前登录用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 校验要回复的私信状态
        Message existsMessage = messageService.selectById(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        // 不能给⾃⼰回复
        if (user.getId() == existsMessage.getPostUserId()) {
            // 返回错误描述
            return AppResult.failed("不能回复自己的私信");
        }
        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId()); // 发送者
        message.setReceiveUserId(existsMessage.getPostUserId()); // 接收者
        message.setContent(content); // 内容
        // 调⽤Service
        messageService.reply(repliedId, message);
        // 返回结果
        return AppResult.success();
    }



}
